package server;

import org.apache.commons.fileupload.ProgressListener;

import java.io.PrintWriter;

/**
 * Created by IntelliJ IDEA.
 * User: sam
 * Date: 22/04/12
 * Time: 17:00
 * To change this template use File | Settings | File Templates.
 */


/**
 * http://stackoverflow.com/questions/254719/file-upload-with-java-with-progress-bar
 */
public class MFProgressListener implements ProgressListener {

    private long progress;
    private long donePBytesRead = 0;
    private PrintWriter out;

    public MFProgressListener(PrintWriter out) {
        this.out = out;
    }

    public void update(long pBytesRead, long pContentLength, int pItems) {

        /**
         * 1 Byte = 8 Bit
           1 Kilobyte = 1024 Bytes
         */

        if(pBytesRead > donePBytesRead) {

            // Have to use double, otherwise result is 0 regardless (any division with decimal needs to be double)

            double dBytesRead = pBytesRead/1024;
            double dContentLength = pContentLength/1024;

            double tmp = (dBytesRead/dContentLength);

            progress = (long) (tmp * 100);

            //out.write(""+progress);

            System.out.println("Upload % " +progress);

            if (pContentLength == -1) {
               //System.out.println("So far, " + pBytesRead + " bytes have been read.");
            } else {
               //System.out.println("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read.");
           }

           donePBytesRead = pBytesRead;
        }

        if(progress == 100) {
            donePBytesRead = 0;
        }
   }

    public String getPercentDone() {
        return ""+progress;
    }
}